<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2018/1/2
 * Time: 11:49
 */

namespace app\site\controller;


use app\api\model\user\Users;
use app\common\model\BuyBill;
use app\common\utils\ValueValidUtil;
use think\exception\HttpResponseException;
use think\Request;
use think\Response;

class Wechat
{
    public function pay(Request $request) {

        $uid = checkUserLogin(true);

        $redirect_url = $request->get('redirect_url');
        $this->validUrl($redirect_url,'redirect_url');

        $openid = $request->param('openid');
        if (empty($openid)) {
            require_once dirname(dirname(__DIR__)).'/common/lib/wxpay/WxPay.JsApiPay.php';
            $jsApi = new \JsApiPay();
            $openid = $jsApi->GetOpenid();
        }

        $urlParams = ['openid' => $openid];

        if ($redirect_url) {
            // 如果有redirect_url参数，则跳转回去处理
            header('Location: ' . $this->addQueryString($redirect_url, $urlParams));
            exit;
        }

        $success_url = $request->get('success_url');
        $this->validUrl($success_url,'success_url');
        $cancel_url = $request->get('cancel_url');
        $this->validUrl($cancel_url,'cancel_url');
        $bill_id = $request->get('bill_id');
        if (!is_numeric($bill_id)) $this->errorMsg('订单ID为整数');
        $headers = [
            'appid' => 1,
            'appsecret' => '39b3567d0b8ac89c025b78beec26acb0',
            'uid' => $uid,
            'token' => $request->get('token'),
        ];
        $params = [
            'ext' => $openid,
            'bill_id' => $bill_id,
            'pay_method' => 2,
            'client_type' => 2,
        ];
        $bill = BuyBill::get($params['bill_id']);
        if (empty($bill)) $this->errorMsg('无效订单ID');

        return view('pay', [
            'params' => json_encode($params,JSON_UNESCAPED_UNICODE),
            'headers' => json_encode($headers),
            'bill' => $bill,
            'success_url' => $success_url,
            'cancel_url' => $cancel_url,
        ]);
    }

    private function validUrl($val, $msg) {
        if (empty($val)) return;
        if (!ValueValidUtil::url($val)) {
            $this->errorMsg($msg.'无效URL');
        }
    }

    private function errorMsg($msg) {
        throw new HttpResponseException(Response::create($msg,'',404));
    }

    /**
     * url添加参数
     *
     * @param $url
     * @param $params
     * @return string
     */
    private function addQueryString($url, $params) {
        $urlData = parse_url($url);

        if (empty($urlData['query'])) $urlData['query'] = http_build_query($params);
        else $urlData['query'] .= '&' . http_build_query($params);

        $url = '';
        if (isset($urlData['scheme'])) $url .= $urlData['scheme'] . '://';
        if (isset($urlData['host'])) $url .= $urlData['host'];
        if (isset($urlData['port'])) $url .= ':'.$urlData['port'];

        $url .= $urlData['path'].'?'.$urlData['query'];

        if (isset($urlData['fragment'])) $url .= '#'.$urlData['fragment'];

        return $url;
    }
}